package com.linewow.xhyy.nihaonew.activity;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.support.v4.app.FragmentManager;
import android.util.Log;
//import com.hyphenate.EMCallBack;
//import com.hyphenate.EMMessageListener;
//import com.hyphenate.chat.EMClient;
//import com.hyphenate.chat.EMConversation;
//import com.hyphenate.chat.EMMessage;
//import com.linewow.xhyy.fuckhrxb.domain.EaseUser;
//import com.linewow.xhyy.hrxb.DemoHelper;
//import com.linewow.xhyy.hrxb.db.DemoDBManager;
import com.linewow.xhyy.hrxb.message.HrXbMessageEvent;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.application.NiHaoApp;
import com.linewow.xhyy.nihaonew.base.BaseFragmentActivity;
import com.linewow.xhyy.nihaonew.control.FrameActDataControl;
import com.linewow.xhyy.nihaonew.databinding.ActivityFrameBinding;
import com.linewow.xhyy.nihaonew.entity.user.HuanXinUserInfo;
import com.linewow.xhyy.nihaonew.event.MessageEvent;
import com.linewow.xhyy.nihaonew.media.EaseVoiceRecorder;
import com.linewow.xhyy.nihaonew.net.NihaoNetWork;
import com.linewow.xhyy.nihaonew.util.CommonUtil;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 主框架界面
 */
public class FrameActivity extends BaseFragmentActivity {
    public String TAG="FrameActivity";
    private ActivityFrameBinding binding;
    private FragmentManager fm;
    private EaseVoiceRecorder recorder;
    public FrameActDataControl frameActDataControl;

    @Override
    public void initView() {
        super.initView();
        LogE("初始化了");
        binding= DataBindingUtil.setContentView(FrameActivity.this,R.layout.activity_frame);
        fm=getSupportFragmentManager();
        frameActDataControl=new FrameActDataControl(fm);
        binding.setFrameActDataControl(frameActDataControl);

        //调起录音权限
        recorder=new EaseVoiceRecorder(handler);
        recorder.setPathFlag(true);
        Observable.timer(5, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        Log.e(TAG,"延时了"+aLong);
                        recorder.startRecording(FrameActivity.this);
                    }
                });

        Observable.timer(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(Schedulers.newThread())
                .subscribe(new Action1<Long>() {
                    @Override
                    public void call(Long aLong) {
                        try{
                            recorder.stopRecoding();
                        }catch (Exception e){
                            Log.e(TAG,"错误信息"+e.getMessage());
                        }

                    }
                });
        refreshUIWithMessage();
    }

    Handler handler=new Handler();

    @Override
    public void initList() {
        super.initList();
        EventBus.getDefault().register(FrameActivity.this);
//        EMClient.getInstance().chatManager().addMessageListener(messageListener);//环信监听
        if(CommonUtil.ChineseLocale(FrameActivity.this)){
            Log.e(TAG,"这是中文");
            NiHaoApp.EnglishFlag=false;
        }else{
            NiHaoApp.EnglishFlag=true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(FrameActivity.this);
//        EMClient.getInstance().chatManager().removeMessageListener(messageListener);
//        logout();
    }



    /**
     * 登录 登出
     * @param messageEvent
     */
    @Subscriber(tag = "login",mode = ThreadMode.POST)
    public void getLoginMessageEvent(MessageEvent messageEvent){

        Log.e(TAG,"登录了");

        frameLogin();

    }

    private void frameLogin() {


        /**
         * 先请求出账号和密码来！
         */
        String codeToken=null;
        try {
            codeToken= URLEncoder.encode(NiHaoApp.token,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        NihaoNetWork.getNiHaoService()
                .huanxinUser(codeToken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<HuanXinUserInfo>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                    @Override
                    public void onNext(HuanXinUserInfo huanXinUserInfo) {
                        NiHaoApp.nick=huanXinUserInfo.nickname;
                        Log.e(TAG,"昵称-->"+NiHaoApp.nick);
                        hrxbLogin(huanXinUserInfo);
                    }
                });
    }

    @Subscriber(tag = "logout",mode = ThreadMode.POST)
    public void getLogOutMessageEvent(MessageEvent messageEvent){
        Log.e(TAG,"退出了");
        showFrameActivity();

//        EMClient.getInstance().logout(true, new EMCallBack() {
//
//            @Override
//            public void onSuccess() {
//                // TODO Auto-generated method stub
//                Log.e(TAG, "退出成功了");
//                showFrameActivity();
//            }
//
//            @Override
//            public void onProgress(int progress, String status) {
//                // TODO Auto-generated method stub
//
//            }
//
//            @Override
//            public void onError(int code, String message) {
//                // TODO Auto-generated method stub
//                Log.e(TAG, "退出失败了");
//
//            }
//        });
    }

    @Subscriber(tag = "ChatActivity",mode = ThreadMode.MAIN)
    public void  chatActivityDestroy(MessageEvent messageEvent){
        refreshUIWithMessage();
    }

    public void showFrameActivity(){
        Intent intent=new Intent(FrameActivity.this,FrameActivity.class);
        startActivity(intent);
    }


//    EMMessageListener messageListener = new EMMessageListener() {
//
//        @Override
//        public void onMessageReceived(List<EMMessage> messages) {
//            refreshUIWithMessage();
//            Log.e(TAG, "方法：EMMessageListener_onMessageReceived");
//        }
//
//        @Override
//        public void onCmdMessageReceived(List<EMMessage> messages) {
//        }
//
//        @Override
//        public void onMessageReadAckReceived(List<EMMessage> messages) {
//            Log.e(TAG, "方法：onMessageReadAckReceived");
//        }
//
//        @Override
//        public void onMessageDeliveryAckReceived(List<EMMessage> message) {
//            Log.e(TAG, "方法：onMessageDeliveryAckReceived");
//        }
//
//        @Override
//        public void onMessageChanged(EMMessage message, Object change) {
//            Log.e(TAG, "方法：onMessageChanged");
//        }
//    };

    private void refreshUIWithMessage() {
        int count = getUnreadMsgCountTotal();
        Log.e(TAG, "接受到的信息的数目" + count);
        frameActDataControl.setMessageNum(count);
        EventBus.getDefault().post(new HrXbMessageEvent(""), "MessageFragment");//发送给回话列表
    }


    private int getUnreadMsgCountTotal() {
        int unreadMsgCountTotal = 0;
        int chatroomUnreadMsgCount = 0;
//        unreadMsgCountTotal = EMClient.getInstance().chatManager().getUnreadMsgsCount();
//        for (EMConversation conversation : EMClient.getInstance().chatManager().getAllConversations().values()) {
//            if (conversation.getType() == EMConversation.EMConversationType.ChatRoom)
//                chatroomUnreadMsgCount = chatroomUnreadMsgCount + conversation.getUnreadMsgCount();
//        }
        return unreadMsgCountTotal - chatroomUnreadMsgCount;
    }



    private void hrxbLogin(HuanXinUserInfo huanXinUserInfo) {
//        DemoDBManager.getInstance().closeDB();
//        DemoHelper.getInstance().setCurrentUserName(huanXinUserInfo.username);
        Log.e(TAG,"名称"+huanXinUserInfo.nickname+"---"+huanXinUserInfo.password);
        showFrameActivity();
//        EMClient.getInstance().login(huanXinUserInfo.username, huanXinUserInfo.password, new EMCallBack() {
//            @Override
//            public void onSuccess() {
//                EMClient.getInstance().groupManager().loadAllGroups();
//                EMClient.getInstance().chatManager().loadAllConversations();
//
//                // update current user's display name for APNs
//                DemoHelper.getInstance().getUserProfileManager().asyncGetCurrentUserInfo();
//
//                EaseUser user=DemoHelper.getInstance().getUserProfileManager().getCurrentUserInfo();
//                Log.e(TAG,"当前用户的头像"+user.getAvatar());
//
//                showFrameActivity();
//
//            }
//
//            @Override
//            public void onError(int i, String s) {
//                Log.e(TAG, "错误代码：" + i + "登录失败了:" + s);
//            }
//
//            @Override
//            public void onProgress(int i, String s) {
//                Log.e(TAG,"正在登录中"+s);
//            }
//        });
    }


    private void logout() {
//        EMClient.getInstance().logout(true, new EMCallBack() {
//
//            @Override
//            public void onSuccess() {
//                // TODO Auto-generated method stub
//                Log.e(TAG, "退出成功了");
//            }
//
//            @Override
//            public void onProgress(int progress, String status) {
//                // TODO Auto-generated method stub
//
//            }
//            @Override
//            public void onError(int code, String message) {
//                // TODO Auto-generated method stub
//                Log.e(TAG, "退出失败了");
//            }
//        });
    }
}
